package com.example.wan_android.adapter

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.example.wan_android.BR
import com.example.wan_android.R
import com.example.wan_android.core.CoreViewHolder
import com.example.wan_android.databinding.AdapterPaperBinding
import com.example.wan_android.http.bean.PaperInfoData
import com.example.wan_android.viewmodel.PaperShowViewModel

class PaperAdapter(vm: PaperShowViewModel) :
    CoreAdapter<AdapterPaperBinding, PaperShowViewModel, PaperInfoData>(
        BR.data,
        BR.viewModel,
        vm
    ) {

    companion object {
        private const val PAYLOAD_UPDATE_COLLECT_STATE = "update_collect_state"
    }

    override fun getItemLayoutId(viewType: Int): Int {
        return R.layout.adapter_paper
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CoreViewHolder {
        val holder = super.onCreateViewHolder(parent, viewType)

        holder.binding.root.findViewById<ImageView>(R.id.iv_love).setOnClickListener {
            val position = holder.adapterPosition
            if(mListData[position].collect) {
                mViewModel?.unCollection(mListData[position].id)
            } else {
                mViewModel?.collection(mListData[position].id)
            }
            mListData[position].collect = !mListData[position].collect
            notifyItemChanged(position, PAYLOAD_UPDATE_COLLECT_STATE)
        }
        return holder
    }

    override fun onBindViewHolder(
        holder: CoreViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        } else {
            holder.binding.root.findViewById<View>(R.id.iv_love).isSelected =
                mListData[position].collect
        }
    }

    override fun onBindViewHolder(holder: CoreViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        holder.binding.root.findViewById<View>(R.id.iv_love).isSelected = mListData[position].collect
        holder.binding.root.findViewById<TextView>(R.id.tv_new).visibility =
            if (mListData[position].niceDate.contains("小时")) {
                TextView.VISIBLE
            } else {
                TextView.GONE
            }
    }

}